package cn.melonlib.aap.user.comp.service;

import cn.melonlib.aap.user.model.entity.Account;
import cn.melonlib.aap.user.model.entity.School;
import cn.melonlib.aap.user.model.enums.AccountType;
import cn.melonlib.cores.commons.comp.service.impl.WorkerBasicService;
import cn.melonlib.cores.jpa.model.bean.impl.DefaultQuery;
import cn.melonlib.cores.model.anno.*;
import org.intellij.lang.annotations.Language;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;

@Service
@WorkerService(
        module = "org"
        ,model = @WorkerModel(
                modelType = School.class
)
)
@WorkerComment("学校管理")
public class SchoolService extends WorkerBasicService<School> {

    @Resource
    private AccountManagerService accountManagerService;

    @WorkerComment("创建学校")
    @WorkerStore
    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    public School createSchool(
            @WorkerParameter(value = "school",comment = "学校信息",required = true) School school,
            @WorkerParameter(value = "password",comment = "登陆密码",required = true) String password) throws Exception{
        @Language("HQL") String validSchool="from School where code=?1";
        List<School> schools=dao.<List<School>,DefaultQuery>search(new DefaultQuery(validSchool, List.of(school.getCode()))).getResult();
        Assert.isTrue(schools.isEmpty(),"学校编号已被占用");
        school= dao.save(school).getResult();
        Account account=new Account();
        account.setAccount(school.getCode());
        account.setTenantId(school.getCode());
        account.setTenant(getJsonMapper().writeValueAsString(school));
        account.setAccountTypes(getJsonMapper().writeValueAsString(List.of(AccountType.ORGANIZATION.name())));
        account.setActived(true);
        accountManagerService.createAccount(account,password);
        return school;
    }
}
